﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pingy
{
    public static class Parser
    {
        public static IPRange[] ParseInput(string input)
        {
            input = input.Replace(" ", "");
            string[] ipRangesStr = input.Split(',');

            IPRange[] ipRanges = new IPRange[ipRangesStr.Length];
            for (int i = 0; i < ipRangesStr.Length; i++)
            {
                string range = ipRangesStr[i];
                ipRanges[i] = ParseIPRange(range);
            }

            return ipRanges;
        }

        private static IPRange ParseIPRange(string ipRange)
        {
            string[] subnetStr = ipRange.Split('.');
            if (subnetStr.Length != 4)
                throw new ArgumentException("Subnet should have exactly 4 octets: " + ipRange);

            IPRange range = new IPRange();
            for (int i = 0; i < subnetStr.Length; i++)
            {
                Subnet subnet = new Subnet();

                string sub = subnetStr[i];
                sub = sub.Trim();

                if (sub.Contains('-'))
                {
                    string[] subnetRange = sub.Split('-');
                    if (subnetRange.Length != 2)
                        throw new ArgumentException("Unable to parse octet range: " + sub);

                    byte lower;
                    byte upper;

                    if (!byte.TryParse(subnetRange[0], out lower))
                        throw new ArgumentOutOfRangeException("sub", sub, "Each octet of an IP Address should be between 0 and 255.");
                    if (!byte.TryParse(subnetRange[1], out upper))
                        throw new ArgumentOutOfRangeException("sub", sub, "Each octet of an IP Address should be between 0 and 255.");

                    subnet.Start = lower;
                    subnet.End = upper;
                }
                else if (sub.Contains('*'))
                {
                    if (sub.Length != 1)
                        throw new ArgumentException("Unable to parse octet range " + sub);

                    subnet.Start = 0;
                    subnet.End = 255;
                }
                else
                {
                    byte value;
                    if (!byte.TryParse(sub, out value))
                        throw new ArgumentOutOfRangeException("sub", sub, "Each octet of an IP Address should be between 0 and 255.");

                    subnet.Start = subnet.End = value;
                }

                range.Subnets[i] = subnet;
            }

            return range;
        }
    }
}
